<?php

namespace App\Http\Controllers;

use App\Http\Requests\NodeStoreRequest;
use App\Models\Nodes;
use App\Models\RoleNodes;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NodeController extends Controller
{
    /** 节点列表
     * @return JsonResponse
     */
    public function index(): \Illuminate\Http\JsonResponse
    {
        $nodes = Nodes::where('pid', 0)->with(['children' => function ($query) {
            $query->with('children'); // 递归加载子节点的子节点
        }])->get();
        return response()->json(['data' => $nodes]);
    }

    /** 新增节点
     * @param NodeStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(NodeStoreRequest $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->safe()->only(['name', 'path', 'pid', 'icon', 'sort', 'status', 'is_menu', 'method']);
        Nodes::create($data);
        return response()->json(['message' => '新增节点成功']);
    }

    /** 查看节点详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id): \Illuminate\Http\JsonResponse
    {
        $node = Nodes::find($id);
        return response()->json(['data' => $node]);
    }

    /** 更新节点
     * @param NodeStoreRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function update(NodeStoreRequest $request, $id): \Illuminate\Http\JsonResponse
    {
        $node = Nodes::find($id);
        $node->update($request->safe()->only(['name', 'path', 'pid', 'icon', 'sort', 'status', 'is_menu', 'method']));
        return response()->json(['message' => '更新节点成功']);
    }

    /**
     * 删除节点
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id): \Illuminate\Http\JsonResponse
    {
        // 查询是否有子节点
        $children = Nodes::where('pid', $id)->first();
        if ($children) {
            return response()->json(['message' => '请先删除子节点']);
        }
        Nodes::destroy($id);
        RoleNodes::where('node_id', $id)->delete();
        return response()->json(['message' => '删除节点成功']);
    }

}
